<script>
import { createTools, deleteTools, getToolID, updateTools } from '@/api/tool.js'
import { getAppsByToolId, getAppsByIds } from '@/api/app.js'
// import outputEdit from "@/components/AppCreate/output/outputEdit.vue";
import JsonCodeMirror from '@/components/JavascriptCodemirror/index.vue'
import JsonEditor from 'vue-json-editor'
import { getDetailInfo } from '@/api/user'
import '@/styles/common.css'
export default {
  name: 'EditTool',
  components: {
    json_code: JsonCodeMirror,
    JsonEditor
  },
  data() {
    return {
      radio: '',
      // 确认类型，是修改还是新建
      isEdit: false,
      // 要修改的id
      id: '',
      // 表单内容
      toolForm: {},
      // 参数可选类型
      paraType: [
        'string',
        'integer',
        'boolean',
        'text'
      ],
      value: '',
      param_handle: [
        {value: 'query', lable: 'query', comment: '参数全部拼接进url中'},
        {value: 'body', lable: 'body', comment: '参数全部写进请求体中'},
        {value: 'llm', lable: 'llm', comment: '适配普通llm接口形式'},
        {value: 'llm-image', lable: 'llm-image', comment: '适配图生文形式llm接口'},
        {value: 'generate-image', lable: 'generate-image', comment: '适配文生图形式llm接口'}
      ],
      // 当前工具创建者的用户名
      userName: '',
      // 表单提交时验证
      rules: {
        name: [
          { required: true, message: ('工具名称不能为空!!!'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: ('工具描述不能为空!!!'), trigger: 'change' }
        ],
        host: [
          { required: true, message: ('主机域名不能为空!!!'), trigger: 'blur' }
        ],
        method: [
          { required: true, message: ('请至少选择一个工具方法!!!'), trigger: 'blur' }
        ],
        param_handle: [
          { required: true, message: ('请至少选择一种参数处理方法!!!'), trigger: 'blur' }
        ],
      },
      listLoading: false,
      appList: [],
      totalNumber: 0
    }
  },
  computed: {
    showBasicInformation: function() {
      return (this.radio === this.$t('basicInformation'))
    },
    showRelatedApps: function() {
      return (this.radio === this.$t('relatedApps'))
    }
    // parameters: {
    //   get() {
    //     return this.toolForm.parameters ? JSON.stringify(this.toolForm.parameters) : ''
    //   },
    //   set(val) {
    //   }
    // }
  },
  created() {
    this.id = this.$route.query.id
    this.isEdit = this.$route.query.is_edit
    this.radio = this.$t('basicInformation')
    this.listLoading = false
    if (this.isEdit) {
      // 若是编辑 请求工具内容并填入表格中
      getToolID(this.id).then(response => {
        this.getUserNameById(response.creator_id)

        console.log(response.data)
        const data = response
        console.log(data)
        this.toolForm = Object.assign({}, data)

        // 调整host的内容
        // this.toolForm.host = this.toolForm.host.slice(8)
        /* this.$message({
          message: '获取成功',
          type: 'success'
        }) */
        // 需要将输出结构和参数序列化以展示
        this.toolForm.output_structure = JSON.stringify(this.toolForm.output_structure, null, 2)
        this.toolForm.parameters = JSON.stringify(this.toolForm.parameters, null, 2)
        // this.toolForm.url = this.toolForm.url.split('?')[1]
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '获取失败',
          type: 'error'
        })
      })
    }
  },
  watch: {
    radio(newVal) {
      if (newVal === this.$t('relatedApps')) {
        this.loadRelatedApps();
      }
    }
  },
  methods: {
    // 添加参数
    pushPara() {
      if (!('parameters' in this.toolForm)) {
        this.$set(this.toolForm, 'parameters', [])
      }
      this.toolForm.parameters.push(
        {
          name: '',
          description: '',
          type: '',
          tool_id: 0,
          value: ''
        }
      )
      console.log(this.toolForm.parameters)
    },
    // 删除参数
    popPara(index) {
      this.toolForm.parameters.splice(index, 1)
    },
    // 编辑
    toEdit() {
      this.$router.push({
        path: '/tool/index/edit',
        query: {
          id: this.id,
          is_edit: true
        }
      })
    },
    // 删除
    toDelete(id) {
      this.$confirm(this.$t('tool_delete_tips'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        // 删除该tool
        deleteTools(this.id).then(response => {
          console.log(response.data)
          this.$router.push({
            path: '/tool/index'
          })
          this.$message({
            message: this.$t('delete_success_tips'),
            type: 'success'
          })
        }).catch(error => {
          console.log(error)
          this.$message({
            message: this.$t('delete_error_tips'),
            type: 'error'
          })
        })
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('delete_cancel_tips'),
          type: 'info'
        })
      })
    },
    // 将Wed, 28 Aug 2024 19:59:45 GMT字符串，转换为2024-08-28 19:59:45
    stringToDate(dateString) {
      if (typeof dateString !== 'string') {
        // 创建 Date 对象
        const date = new Date(dateString['$date'])

        // 获取年份
        const year = date.getUTCFullYear()
        // 获取月份，注意要加 1，因为月份是从 0 开始的
        const month = String(date.getUTCMonth() + 1).padStart(2, '0')
        // 获取日期
        const day = String(date.getUTCDate()).padStart(2, '0')
        // 获取小时
        const hours = String(date.getUTCHours()).padStart(2, '0')
        // 获取分钟
        const minutes = String(date.getUTCMinutes()).padStart(2, '0')
        // 获取秒
        const seconds = String(date.getUTCSeconds()).padStart(2, '0')

        // 组合成指定格式的字符串
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      // 正则表达式来匹配日期和时间的各个部分
      const regex = /^(\w+),\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d{2}):(\d{2}):(\d{2})\s+GMT$/
      const parts = dateString.match(regex)

      if (!parts) {
        throw new Error('Invalid date string format')
      }

      // 从匹配结果中提取年、月、日等
      const [, , day, monthShort, year, hour, minute, second] = parts

      // 映射月份缩写到数字（注意月份是从0开始的）
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
      const monthIndex = months.indexOf(monthShort)
      if (monthIndex === -1) {
        throw new Error('Invalid month in date string')
      }

      // 创建一个新的Date对象
      const date = new Date(Date.UTC(year, monthIndex, day, hour, minute, second))

      // 格式化日期时间为YYYY-MM-DD HH:MM:SS
      const formattedDate = `${date.getUTCFullYear()}-${(date.getUTCMonth() + 1).toString().padStart(2, '0')}-${date.getUTCDate().toString().padStart(2, '0')} ${date.getUTCHours().toString().padStart(2, '0')}:${date.getUTCMinutes().toString().padStart(2, '0')}:${date.getUTCSeconds().toString().padStart(2, '0')}`

      return formattedDate
    },
    // 根据创建者id获得创建者的名字
    getUserNameById(id) {
      getDetailInfo(id).then(res => {
        this.userName = res.data.name
      })
      console.log('-----------', this.userName)
    },

    loadRelatedApps() {
      this.listLoading = true;
      getAppsByToolId(this.id)
        .then(response => {
          // 记录总数
          this.totalNumber = response.length;
          console.log("totalNumber: " + this.totalNumber)
          if (this.totalNumber === 0) {
            this.listLoading = false;
            return;
          }
          // 将数组转换为逗号分隔的字符串
          const appIds = response.join(',');
          getAppsByIds(appIds).then(response => {
            this.appList = response;
          })
        })
        .catch(error => {
          this.$message.error('获取关联应用失败: ' + error.message);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 关联应用详情
    toDetail(id) {
      this.$router.push({ path: '/app_management/index/details/', query: { id: id }})
    },
    // 运行关联应用
    toRun(id) {
      this.$router.push({ path: `/app_management/index/details/chatExecutingUser`, query: { id: id }})
    },
  }
}
</script>

<template>
  <div class="app-container">
    <el-row class="paragraph_spacing">
      <div class="clearfix">
        <!--项目图标-->
        <div class="left" style="padding-top:15px;width:100px;float:left">
          <img alt="icon" src="@/views/login/img/tool.png">
        </div>
        <!--项目简介-->
        <div class="left" style="width:85%;height: fit-content;float:none;margin-left: 120px">
          <p class="large">
            <span style="margin-right: 10px;">{{ toolForm.name }}</span>
            <!-- <el-tag style="margin-right: 10px" :type="appDetail.status | statusFilter" @click="refreshStatus">
              {{ appDetail.status }}
            </el-tag> -->
            <!-- <i style="vertical-align: -3px; color: #606266" class="el-icon-refresh-right" @click="refreshStatus" /> -->
          </p>
          <span class="base">{{ toolForm.description }}</span><br>
          <!--          <span class="base">{{ $t('namespace') }}：{{ projectDetail.namespace }}</span><br>-->
          <br>
          <!-- 展示应用的开发者 -->
          <!--            <span class="base">{{ $t('developer')+ ': ' + appDetail.creator_name }}</span><br>-->
          <span class="base">{{ $t('creator')+ ': ' + this.userName }}</span><br>
          <!-- <span class="base">{{ $t('original_problem') + ': ' + (typeof appDetail.app_requirement === 'undefined' ? '' : appDetail.app_requirement) }}</span><br>-->
          <span class="base">{{ $t('creation_time') + ': ' + stringToDate(toolForm.created_at) }}</span><br>
          <span class="base">{{ $t('update_time') + ': ' + stringToDate(toolForm.updated_at) }}</span><br>
          <!--          <span class="base">{{ $t('creation_time') + ': ' }}</span><br>-->
          <!--          <span class="base">{{ $t('update_time') + ': ' }}</span><br>-->
          <!--<span class="base">{{ $t('create') }}{{ $t('time') }}：{{ appDetail.createTime }}</span>-->
        </div>
      </div>
    </el-row>
    <el-row type="flex" justify="space-between" class="row_spacing">
      <el-col :span="12">
          <el-radio-group v-model="radio">
            <el-radio-button id="1" :label="$t('basicInformation')" />
            <el-radio-button id="2" :label="$t('relatedApps')" />
          </el-radio-group>
        </el-col>
      <div style="float: right">
        <el-button-group>
          <el-button  v-if="$store.getters.isAdmin()"
            icon="el-icon-edit"
            @click="toEdit"
          > {{ $t('edit') }}
          </el-button>
          <el-button  v-if="$store.getters.isAdmin()"
            icon="el-icon-delete"
            @click="toDelete"
          > {{ $t('delete') }}
          </el-button>
        </el-button-group>
      </div>
    </el-row>
    <!--    <el-row type="flex" justify="space-between" class="row_spacing">-->

    <!--      <el-col :span="20" class="clearfix">-->
    <!--        <el-button-group class="right">-->
    <!--          <el-button-->
    <!--            icon="el-icon-edit"-->
    <!--            @click="toEdit"-->
    <!--          > {{ $t('edit') }}-->
    <!--          </el-button>-->
    <!--          <el-button-->
    <!--            icon="el-icon-delete"-->
    <!--            @click="toDelete"-->
    <!--          > {{ $t('delete') }}-->
    <!--          </el-button>-->
    <!--        </el-button-group>-->
    <!--      </el-col>-->
    <!--    </el-row>-->
    <div v-if="showBasicInformation" style="background-color: white;padding: 20px 20px;">
      <div class="create-container">
        <el-form ref="toolForm" :model="toolForm" :rules="rules" label-width="120px">
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <!-- tool的名称 -->
              <el-row>
                <el-col :span="16">
                  <el-form-item :label="$t('name')" prop="name">
                    <el-input v-model="toolForm.name" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- tool的描述 -->
              <el-form-item :label="$t('description')" prop="description">
                <el-input v-model="toolForm.description" :rows="4" type="textarea" disabled />
              </el-form-item>
              <!-- tool的来源 -->
              <el-form-item :label="$t('source')" prop="source">
                <el-input v-model="toolForm.source" type="text" disabled />
              </el-form-item>
              <!-- tool的主机域名 -->
              <el-form-item :label="$t('host')" prop="host">
                <el-input v-model="toolForm.host" type="text" disabled />
              </el-form-item>
              <!-- tool的请求方法 -->
              <el-form-item :label="$t('method')" prop="method">
                <el-radio-group v-model="toolForm.method" disabled>
                  <el-radio label="get" />
                  <el-radio label="put" />
                  <el-radio label="delete" />
                  <el-radio label="post" />
                </el-radio-group>
              </el-form-item>
              <!-- tool的参数处理 -->
              <!-- <el-form-item :label="$t('parameter') + $t('handle')" prop="param_handle">
                <el-select disabled
                  v-model="toolForm.param_handle"
                  placeholder="请选择"
                  style="width: 30%"
                >
                  <el-option
                    v-for="item in param_handle"
                    :key="item.value"
                    :label="item.lable"
                    :value="item.value">
                    <el-tooltip :content="item.comment" placement="top">
                      <span>{{ item.lable }}</span>
                    </el-tooltip>
                  </el-option>
                </el-select>
              </el-form-item> -->
              <!-- 可选的参数填写 -->
              <el-form-item :label="$t('Input_parameter')" prop="parameters">
                <json_code v-model="toolForm.parameters" :read-only="true" :disabled="true"/>
                <!--json-editor v-model="toolForm.parameters" mode="code" :show-btns="false" lang="json" /-->
              </el-form-item>
              <el-form-item :label="$t('Output_parameter')" prop="parameters">
                <json_code v-model="toolForm.output_structure" :read-only="true" :disabled="true"/>
                <!--json-editor v-model="toolForm.output_structure" mode="code" :show-btns="false" lang="zh" /-->
              </el-form-item>

              <!-- 动态添加query参数 -->
              <el-form-item
                v-if="$store.getters.isAdmin()"
                :label="''"
                prop="params" >
                <template slot="label">
                  入参适配<br>（URL）
                </template>
                <json_code v-model="toolForm.url" :readOnly="true" :disabled="true"/>
                <!-- <el-table :data="toolForm.params" style="width: 100%">
                  <el-table-column prop="name" label="参数名" width="180">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.name"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="value" label="参数值" width="180">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.value"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="type" label="类型" width="180">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.type" placeholder="请选择">
                        <el-option label="String" value="string"></el-option>
                        <el-option label="Integer" value="integer"></el-option>
                        <el-option label="Boolean" value="boolean"></el-option>
                        <el-option label="Text" value="text"></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="说明">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.description"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button size="mini" type="danger" @click="handleDeleteParam(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button type="primary" @click="handleAddParam">添加参数</el-button> -->
              </el-form-item>
              <!-- 输入body的区域 -->
              <el-form-item
                v-if="$store.getters.isAdmin()"
                :label="''"
                prop="header">
                <template slot="label">
                  入参适配<br>（header）
                </template>
                <json_code v-model="toolForm.header" :readOnly="true" :disabled="true"/>
                <!-- 或者使用普通的文本区域 -->
                <!-- <el-input v-model="toolForm.body" type="textarea" :rows="4" placeholder="请输入JSON格式的body数据"></el-input> -->
              </el-form-item>
              <el-form-item
                v-if="$store.getters.isAdmin()"
                :label="''"
                prop="body">
                <template slot="label">
                  入参适配<br>（body）
                </template>
                <json_code v-model="toolForm.body" :readOnly="true" :disabled="true"/>
                <!-- 或者使用普通的文本区域 -->
                <!-- <el-input v-model="toolForm.body" type="textarea" :rows="4" placeholder="请输入JSON格式的body数据"></el-input> -->
              </el-form-item>
              <!--            &lt;!&ndash; 保存按钮 &ndash;&gt;-->
              <!--            <el-form-item>-->
              <!--              <el-button type="primary" @click="submitForm">{{ $t('save') }}</el-button>-->
              <!--            </el-form-item>-->
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    
    <div v-if="showRelatedApps">
      <div>
        <el-row>
          <!-- 展示总数totalNumber -->
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="div-show-total base">
              {{ $t("now_have") }} <span class="font-bold">{{ totalNumber }}</span> {{ $t("n") }} {{ $t("application") }}
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-table
            v-loading="listLoading"
            :data="appList"
            :stripe="true"
            element-loading-text="Loading"
            :border="false"
            :header-cell-style="{color:'black'}"
            fit
            highlight-current-row
          >
            <!--          <el-table v-loading="listLoading" :data="this.$store.state.slist" :stripe="true" element-loading-text="Loading" :border="false" :header-cell-style="{color:'black'}" fit highlight-current-row>-->
            <!--            第一列 名称-->
            <el-table-column :label="$t('name')" align="center" width="238px">
              <template v-slot="scope">
                {{ scope.row.app_name }}
              </template>
            </el-table-column>
            <!--            第二列 描述-->
            <el-table-column :label="$t('description')" align="center">
              <template v-slot="scope">
                {{ scope.row.app_description }}
              </template>
            </el-table-column>
            <!-- 如果是管理员，则显示创建者 -->
            <el-table-column v-if="this.$store.getters.isAdmin()" :label="$t('creator')" width="119px" align="center">
              <template v-slot="scope">
                {{ scope.row.creator_name }}
              </template>
            </el-table-column>
            <!--            第三列 更新时间-->
            <el-table-column align="center" :label="$t('create_update_time')" width="238px">
              <template v-slot="scope">
                <div>
                  <!-- {{ scope.row.instruction }} -->
                  {{ stringToDate(scope.row.created_time) }}
                </div>
                <div>
                  {{ stringToDate(scope.row.update_time) }}
                </div>
              </template>
            </el-table-column>
            <!--            第四列 操作-->
            <el-table-column align="center" :label="$t('operation')" width="119px" fixed="right">
              <template v-slot="scope">
                <div>
                  <!-- <div style="display: flex; justify-content: center; margin-bottom: 0;">
                    <div style="margin-right: 10px;">
                      <a href="javascript:void(0)" class="font-blue" @click="toEdit(scope.row.id)">{{ $t('edit') }}</a>
                    </div>
                    <div>
                      <a href="javascript:void(0)" class="font-blue" @click="toDelete(scope.row.id)">{{ $t('delete') }}</a>
                    </div>
                  </div> -->
                  <div style="display: flex; justify-content: center;">
                    <div style="margin-right: 10px;">
                      <a href="javascript:void(0)" class="font-blue" @click="toDetail(scope.row.id)">{{ $t('detail') }}</a>
                    </div>
                    <div>
                      <a href="javascript:void(0)" class="font-blue" @click="toRun(scope.row.id)">{{ $t('run') }}</a>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </div>
    </div>
  </div>
</template>

<style scoped>
.create-container{
  background: #fff;
  padding-top: 20px;
  margin-top: 0;
}
.paragraph_spacing{
  margin-bottom: 20px;
}
</style>
